<template
  ><!---->
  <div id="transfer" style="margin:10px 0">
    <div class="demo-spin-col" v-if="showLoading">
      <Spin fix>
        <Icon type="ios-loading" size="28" class="demo-spin-icon-load"></Icon>
        <div>加载中...请稍后</div>
      </Spin>
    </div>
    <Spin size="large" fix v-if="spinShow">
      <Icon type="ios-loading" size="28" class="demo-spin-icon-load"></Icon>
      <div>移除中...请稍后</div>
    </Spin>
    <Row style="margin-bottom:10px;">
      {{ type === 10 ? '角色' : '团队' }} ： <Tag color="blue">{{ selectGroup.name }}</Tag>
      <div style="float:right;">
        <template v-if="isDistributed">
          靶场 ：
          <Select filterable
            v-model="rangeId"
            placeholder="请选择靶场"
            @on-change="changeRange"
            :not-found-text="loadingRange ? '加载中...' : '无匹配数据'"
            label-in-value
            filterable
            class="experimental-group"
          >
            <Option
              v-for="range in rangeList"
              :title="range.name"
              :value="range.id"
              :key="range.id"
              :label="range.name"
              >{{ range.name }}</Option
            >
          </Select>
        </template>
        实验组 ：
        <Select filterable
          v-model="expGroupId"
          placeholder="请选择实验组"
          @on-change="changeGroup"
          :not-found-text="loadingGroup ? '加载中...' : '无匹配数据'"
          label-in-value
          filterable
          class="experimental-group"
        >
          <Option
            v-for="group in expGroupList"
            :title="group.name"
            :value="group.id"
            :key="group.id"
            :label="group.name"
            >{{ group.name }}</Option
          >
        </Select>
      </div>
    </Row>
    <Row v-if="selectedUsers.length > 0" style="margin:10px 0;">
      已接入用户：
      <div style="display: flex; flex-wrap: wrap;">
        <Tag
          type="border"
          closable
          color="primary"
          v-for="user in selectedUsers"
          :key="user.userId"
          @on-close="removeAccessGroup"
          :name="user.userId"
          >{{ user.userName }}</Tag
        >
        <Button type="error" @click="clearUsers" size="small">清空用户</Button>
      </div>
    </Row>
    <Transfer
      v-if="!showLoading"
      ref="userTransfer"
      :data="formatAllUsers"
      :list-style="listStyle"
      :target-keys="formatSelectedUsers"
      :render-format="render2"
      :filter-method="filterMethod"
      :operations="['移除', '接入']"
      filter-placeholder="请输入用户名、昵称搜索"
      :titles="['实验组未选用户', '实验组已选用户']"
      filterable
      @on-change="handleChange"
    ></Transfer>
  </div>
</template>

<script>
import {
  getaccessgroupmember,
  getexpergrouplist,
  getexpergroupusers,
  addaccessgroupuser,
  getuserinstance,
  getAllRanges,
  addaccessgroupuserNew,
  removeaccessgroupuserNew
} from '@/api/access_new'
import encryption from '@/libs/encryption.js'
import { mapMutations } from 'vuex'

export default {
  name: 'AccessTransfer',
  props: ['selectGroup', 'show', 'projectId', 'type', 'isDistributed', 'hwType', 'ctfVpn'],
  data() {
    let September = sessionStorage.getItem('November')
    September = JSON.parse(encryption.SelfUseDecrypt(September))
    return {
      spinShow: false,
      USER_ID: September.userId,
      USER_Name: September.nickname,
      listStyle: {
        width: '45%',
        height: '300px'
      },
      allSelectedUsers: [],
      selectDelUserList: [],
      expGroupList: [],
      allUsers: [],
      selectedUsers: [],
      index: 0,
      showLoading: false,
      drillUsers: [],
      expGroupId: '',
      loadingGroup: false,
      loadingRange: false,
      rangeList: [],
      rangeId: ''
    }
  },
  filters: {},
  watch: {
    show: function(val) {
      if (val) {
        this.selectedUsers = []
        this.initTransferQuery()
        this.getAccessUserInfo()
      }
    }
  },
  mounted() {
    if (this.show) {
      this.initTransferQuery()
      this.getAccessUserInfo()
    }
  },
  computed: {
    formatSelectedUsers: function() {
      // 选中的用户的id列表
      return this.selectedUsers.map((user) => user.userId)
    },
    formatAllUsers: function() {
      let arr = this.allSelectedUsers.map((user) => user.userId) // 所有已经加入的用户
      let arr2 = this.selectedUsers.map((user) => user.userId) // 本团队已经选择的用户
      let arr3 = arr.filter((id) => !arr2.includes(id)) // 加入其他团队的用户
      let cArr = this.allUsers
        .filter((user) => {
          // 过滤掉实验员身份的人
          if (user.user) {
            return user.user.type == 'experimenter'
          } else {
            return user
          }
        })
        .filter((user) => !arr3.includes(user.userId)) // 过滤掉加入其他团队的成员，本团队的成员虽然已加入，还是再要穿梭框中展示
      return cArr.map((user) => {
        return {
          key: user.userId,
          label: user.label,
          des: user.expGroupName,
          rangeId: user.user.rangeId
        }
      })
    }
  },
  methods: {
    ...mapMutations('compet', ['setRefreshChatRoom']),
    // 初始化使用，用于后续可选操作
    getAccessUserInfo() {
      this.getAllRanges()
      this.getAccessGroupMember()
      // this.getExpGroupList();
      this.getAllAccessGroupMember()
    },
    //查询所有靶场
    getAllRanges() {
      this.loadingRange = true
      getAllRanges()
        .then((res) => {
          if (res.code == 1) {
            this.rangeList = res.data
            if (this.isDistributed != 1) {
              let selfRange = {}
              this.selfRange = this.rangeList.find((item) => {
                if (item.self == '0') {
                  return item
                }
              })
              this.rangeList = []
              this.rangeList.push(this.selfRange)
            }
            this.rangeList.sort((a, b) => a.self - b.self)
            console.log(this.rangeList, 'this.rangeListthis.rangeList')
            this.rangeId = this.rangeList[0].id
            this.getExpGroupList(this.rangeId)
          } else {
            this.$Message.warning('查询靶场失败')
          }
        })
        .finally(() => {
          this.loadingRange = false
        })
    },
    // 指定接入组，查询组内已接入用户的列表
    getAccessGroupMember() {
      getaccessgroupmember(this.selectGroup.id).then((data) => {
        if (data.code == 1) {
          this.selectedUsers = data.data.items || data.data
        } else if (data.code == -2) {
          this.selectedUsers = []
        } else {
          this.selectedUsers = []
          this.$Message.warning(data.message)
        }
      })
    },
    // 获取场景下所有的已接入用户
    getAllAccessGroupMember() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.$route.query.id
      }
      getuserinstance(params).then((data) => {
        if (data.code == 1) {
          this.allSelectedUsers = data.data.items
        } else if (data.code == -2) {
          this.allSelectedUsers = []
        } else {
          this.allSelectedUsers = []
          this.$Message.warning(data.message)
        }
      })
    },
    // 获取可使用的用户组列表
    getExpGroupList(rangeId) {
      this.loadingGroup = true
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        rangeId: rangeId
      }
      // if(this.type==0){
      // 	params.self=true
      // }
      getexpergrouplist(params)
        .then((data) => {
          if (data.code == 1) {
            let expGroupList = data.data.items
            this.expGroupList = expGroupList.filter((group) => group.userCount > 0)
            if (this.expGroupList.length) {
              this.expGroupId = this.expGroupList[0].id
              this.getExpGroupUsers(this.expGroupList[0])
            }
          }
        })
        .finally(() => {
          this.loadingGroup = false
        })
    },
    // 选择实验组，级联查询组成员
    changeGroup(group) {
      if (group && group.value) {
        let expGroup = {
          name: group.label,
          id: group.value
        }
        this.getExpGroupUsers(expGroup)
      }
    },
    //选择靶场
    changeRange(range) {
      let exprange = {
        name: range.label,
        id: range.value
      }
      this.getExpGroupList(exprange.id)
    },
    // 获取用户组内的成员列表
    getExpGroupUsers(group) {
      return new Promise((resolve, reject) => {
        getexpergroupusers(group.id).then((data) => {
          if (data.code == 1) {
            let users = data.data
            users.forEach(function(user) {
              let label = user.user.username
              if (user.user) {
                label = user.user.username + '(' + user.user.nickname + ')'
              }
              user.label = label
              user.expGroupName = group.name
            })
            this.allUsers = users
            resolve()
          } else {
          }
        })
      })
    },
    // 穿梭框过滤回调
    filterMethod(data, query) {
      return data.label.indexOf(query.trim()) > -1
    },
    // 穿梭框数据有变化
    handleChange(targetKeys, direction, moveKeys) {
      console.log(targetKeys, 11111)
      console.log(this.formatAllUsers)
      //   if (targetKeys.length != 0) {
      //     let rangrid = this.formatAllUsers.find((item) => item.key == targetKeys[0]).rangeId;
      //	 let rangeId = rangrid.rangeId;
      //     console.log(rangeId, 'rangrid');
      //   }
      if (direction == 'left' && (this.hwType == 2 || this.ctfVpn)) {
        this.spinShow = true
        removeaccessgroupuserNew(
          this.$route.query.prjid,
          this.$route.query.id,
          this.selectGroup.id,
          moveKeys
        )
          .then((res) => {
            // console.log('移除',res)
            if (res.code == 1) {
              this.getAccessGroupMember()
              this.getAllAccessGroupMember()
              this.setRefreshChatRoom(new Date().getTime()) // 接入用户修改后，需要记录时间点，通过vuex通知聊天室更新用户列表
            } else {
              this.$Message.warning(res.message)
            }
          })
          .finally(() => {
            this.spinShow = false
          })
      } else {
        this.joinAccessGroup(targetKeys)
      }
    },
    // 移除指定用户
    removeAccessGroup(e, userId) {
      let delUserId = [userId] // 待删除的接入组用户
      let curGroupUserIds = this.selectedUsers.map((user) => user.userId) //当前接入组用户
      let newGroupUsers = curGroupUserIds.filter((id) => !delUserId.includes(id)) // 过滤掉待删除的数据，将剩余用户接入
      if (this.hwType == 2 || this.ctfVpn) {
        //众测或者ctfvpn模式
        removeaccessgroupuserNew(
          this.$route.query.prjid,
          this.$route.query.id,
          this.selectGroup.id,
          [userId]
        ).then((res) => {
          if (res.code == 1) {
            this.getAccessGroupMember()
            this.getAllAccessGroupMember()
            this.setRefreshChatRoom(new Date().getTime()) // 接入用户修改后，需要记录时间点，通过vuex通知聊天室更新用户列表
          } else {
            this.$Message.warning(res.message)
          }
        })
      } else {
        this.joinAccessGroup(newGroupUsers)
      }
    },
    // 为团队接入用户，应该是覆盖式修改
    joinAccessGroup(users) {
      // console.log(users,'usersusersusersusersusers');
      let userIds = [...new Set(users)]
      // console.log(this.formatAllUsers,'formatAllUsersformatAllUsersformatAllUsers');
      // let userss = [];
      // userIds.forEach(items=>{
      // 	let it=this.formatAllUsers.find(item=>item.key===items).rangeId
      // 	console.log(it,'rangId');
      // 	let obj={
      // 		rangeId:'',
      // 		userId:''
      // 	}
      // 	obj.rangeId=it
      // 	obj.userId=items
      // 	userss.push(obj)
      // })
      // console.log(userss,'userssuserssuserss');
      if (this.hwType == 2 || this.ctfVpn) {
        addaccessgroupuserNew(
          this.$route.query.prjid,
          this.$route.query.id,
          this.selectGroup.id,
          userIds
        ).then((data) => {
          if (data.code == 1) {
            this.getAccessGroupMember()
            this.getAllAccessGroupMember()
            this.setRefreshChatRoom(new Date().getTime()) // 接入用户修改后，需要记录时间点，通过vuex通知聊天室更新用户列表
          } else {
            this.$Message.warning(data.message)
          }
        })
      } else {
        addaccessgroupuser(this.selectGroup.id, userIds).then((data) => {
          if (data.code == 1) {
            this.getAccessGroupMember()
            this.getAllAccessGroupMember()
            this.setRefreshChatRoom(new Date().getTime()) // 接入用户修改后，需要记录时间点，通过vuex通知聊天室更新用户列表
          } else {
            this.$Message.warning(data.message)
          }
        })
      }
    },
    // 清空用户，直接接入空数据
    clearUsers() {
      if (this.hwType == 2 || this.ctfVpn) {
        let ids = this.selectedUsers.map((user) => user.userId)
        removeaccessgroupuserNew(
          this.$route.query.prjid,
          this.$route.query.id,
          this.selectGroup.id,
          ids
        ).then((res) => {
          if (res.code == 1) {
            this.getAccessGroupMember()
            this.getAllAccessGroupMember()
            this.setRefreshChatRoom(new Date().getTime()) // 接入用户修改后，需要记录时间点，通过vuex通知聊天室更新用户列表
          } else {
            this.$Message.warning(res.message)
          }
        })
      } else {
        this.joinAccessGroup([])
      }
    },
    // 穿梭框渲染回调
    render2(user) {
      return user.label + '<span style="float:right">' + user.des + '</span>'
    },
    initTransferQuery() {
      this.expGroupId = ''
      this.selectedUsers = []
      this.$refs.userTransfer.$refs.left.query = ''
      this.$refs.userTransfer.$refs.right.query = ''
    }
  }
}
</script>

<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-spin-col {
  height: 200px;
  position: relative;
  border: 1px solid #eee;
}

.experimental-group {
  width: 150px;
}
.experimental-group >>> .ivu-select-selection {
  border-radius: 15px;
  border: 1px solid #cccccc !important;
  outline: 0;
}
.experimental-group >>> .ivu-select-selection:hover {
  border: 1px solid #1563c2 !important;
  box-shadow: 0px 0px 8px #1563c2;
}
.experimental-group >>> .ivu-select-selection:hover i {
  color: #1563c2;
}
</style>
